package com.gxa.weixing.portal.service.impl;


import com.gxa.weixing.core.exception.BusinessException;
import com.gxa.weixing.core.util.SendSms;
import com.gxa.weixing.portal.service.SmsService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * Transactional,业务中使用redis，应该用Transactional管理redis的连接：操作完毕会自动执行关闭连接
 * 阿里规约中规定Transactional必须配置rollbackFor
 *
 * @Author ChenJ
 * @date 2022/01/05 18:14
 */
@Service("smsService")
@Transactional(rollbackFor = Throwable.class)
public class SmsServiceImpl implements SmsService {

    /**
     * 把短信缓存到redis中，30分钟有效时间
     * 切记，要配置key，value的序列化方法RedisSerializable
     */
    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * redis存储的key设为常量
     */
    public static final String VERIFY_SMS = "verify_sms:";

    @Override
    public String sendLoginSms(String phone) throws BusinessException {

        // 1.生成验证码(用工具类的静态方法调用)
        String msgCode = SendSms.getMsgCode();
        // 生成的验证码打印在控制台用于作弊获取
        System.out.println("========验证码========" + msgCode);

        // redis用string类型
        ValueOperations<String, Object> stringOps = redisTemplate.opsForValue();
        // 2.服务器存储验证码并设置失效时间为30分钟
        // key: login_sms:phone
        // value: msgCode
        stringOps.set(VERIFY_SMS+phone,msgCode,30, TimeUnit.MINUTES);

        // 3.调用工具类发送短信给用户
        // String templateParam = "{\"getCode\":\""+msgCode+"\", \"storeName\":\"淘宝直营店\", \"address\":\"阿里巴巴上海分公司\",\"detail\":\"{1}号仓{2}件\"}";
        // String code = "{\"code:\",msgCode}";
        // SendSms.sendSms(phone, code, templateParam);

        // 4. 短信接口返回的数据
        // SendSmsResponse response = sendSms(mobile,templateCode,templateParam);
        // System.out.println("短信接口返回的数据----------------");
        // System.out.println("Code=" + response.getCode());         // OK:成功
        // System.out.println("Message=" + response.getMessage());
        // System.out.println("RequestId=" + response.getRequestId());
        // System.out.println("BizId=" + response.getBizId());
        return msgCode;
    }
}
